package org.yhhhhhhh.ai_jianli.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.yhhhhhhh.ai_jianli.model.User;
import org.yhhhhhhh.ai_jianli.service.JwtService;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT测试控制器
 * 用于测试JWT功能的示例控制器
 */
@RestController
@RequestMapping("/api/test")
public class JwtTestController {

    @Autowired
    private JwtService jwtService;

    /**
     * 测试JWT token生成
     * @param user 用户对象
     * @return 生成的JWT token
     */
    @PostMapping("/generate-token")
    public ResponseEntity<Map<String, Object>> generateToken(@RequestBody User user) {
        try {
            String token = jwtService.generateToken(user);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "Token生成成功");
            response.put("token", token);
            response.put("user", Map.of(
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "email", user.getEmail()
            ));
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Token生成失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 测试JWT token验证
     * @param tokenRequest 包含token的请求
     * @return 验证结果
     */
    @PostMapping("/validate-token")
    public ResponseEntity<Map<String, Object>> validateToken(@RequestBody Map<String, String> tokenRequest) {
        try {
            String token = tokenRequest.get("token");
            
            if (token == null || token.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            boolean isValid = jwtService.validateToken(token);
            String username = jwtService.getUsernameFromToken(token);
            String role = jwtService.getRoleFromToken(token);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("valid", isValid);
            response.put("username", username);
            response.put("role", role);
            response.put("message", isValid ? "Token有效" : "Token无效");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Token验证失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 测试受保护的端点（需要JWT认证）
     * @param authHeader Authorization请求头
     * @return 受保护资源
     */
    @GetMapping("/protected")
    public ResponseEntity<Map<String, Object>> protectedEndpoint(
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "缺少有效的Authorization请求头");
                return ResponseEntity.badRequest().body(response);
            }

            String token = jwtService.extractTokenFromHeader(authHeader);
            User user = jwtService.validateTokenAndGetUser(token);
            
            if (user != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "成功访问受保护的资源");
                response.put("user", Map.of(
                        "id", user.getId(),
                        "username", user.getUsername(),
                        "email", user.getEmail(),
                        "roles", user.getRoles()
                ));
                response.put("data", "这是受保护的数据");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "Token无效或已过期");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "访问受保护资源失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}

